<script setup name="SysDeptIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import DataFormMode from "./modules/FormMode/dataIndex.vue";
import { parseTime } from "@/utils/aidex";
import { listType, delType } from "@/api/system/dict/type";
import { getDicts, delData } from "@/api/system/dict/data";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  dataformModeProps: {
    visible: false,
    id: "",
    dictType: "",
    dictName: ""
  },
  // 搜索
  search: {
    name: "",
    deptId: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],

  //dictDataList
  dictDataList: [],
  dict: {}
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  // 获取部门树
  // getTreeselect();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
// 选取随机颜色
function getRandomColor(index) {
  return data.value.colorList[index % 4];
}
// 截取用户名称
function getShowName(name) {
  if (name.length > 2) {
    name = name.substring(name.length - 2);
  }
  return name;
}

// 获取
function load(row) {
  data.value.dict = row;
  getDicts(data.value.dict.dictType).then((res) => {
    data.value.dictDataList = res.data;
  });
}

function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.dictName && (params.name = data.value.search.dictName);
  console.log("params", params);
  listType(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list;
    pagination.value.total = res.data.total;
  });
}

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
//  获取树选项节点

function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.visible = true;
  }
}

function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
function onDataEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.dataformModeProps.id = row.id;
    data.value.dataformModeProps.dictType = row.dictType;
    data.value.dataformModeProps.dictName = data.value.dict.dictName;
    data.value.dataformModeProps.visible = true;
  }
}
function onDataAdd() {
  data.value.dataformModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.dataformModeProps.dictType = data.value.dict.dictType;
  data.value.dataformModeProps.dictName = data.value.dict.dictName;
  data.value.dataformModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.dictName ||
    data.value.batch.selectionDataList.map((item) => {
      return item.dictName;
    });
  console.log("ids", ids, names);
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delType(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}

function onDataDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.dictLabel ||
    data.value.batch.selectionDataList.map((item) => {
      return item.dictLabel;
    });
  console.log("ids", ids, names);
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delData(ids).then((res) => {
          if (res.code == 200) {
            ElMessage.success({
              message: "删除成功",
              center: true
            });
          }
          load({ dictType: row.dictType });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="字典名称">
                <el-input
                  v-model="data.search.dictName"
                  placeholder="请输入字典名称"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="onAdd">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:circle-plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 380px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @expand-change="load"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="expand">
            <template #default="props" class="data-table">
              <el-row style="height: 40px; line-height: 40px">
                <el-col :span="2"><span></span></el-col>
                <el-col :span="10" style="font-size: 16px; font-weight: 600">
                  <span>{{ props.row.dictName }}</span>
                </el-col>
                <el-col :span="10" style="text-align: right">
                  <el-button-group>
                    <el-button type="primary" @click="onDataAdd" size="small">
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ep:circle-plus" />
                        </el-icon>
                      </template>
                      新增
                    </el-button>
                  </el-button-group>
                </el-col>
                <el-col :span="2">
                  <span></span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="2">
                  <span></span>
                </el-col>
                <el-col :span="20">
                  <el-table :data="data.dictDataList" border width="80%">
                    <el-table-column label="字典标签" prop="dictLabel" />
                    <el-table-column label="字典键值" prop="dictValue" />
                    <el-table-column label="字典排序" prop="dictSort" />
                    <el-table-column label="状态" prop="status">
                      <template v-slot="scope">
                        <el-tag v-if="scope.row.status == '0'" effect="Light"
                          >正常</el-tag
                        >
                        <el-tag v-else effect="Light" type="warning"
                          >停用</el-tag
                        >
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" />
                    <el-table-column label="创建时间" prop="createTime" />
                    <el-table-column label="操作" prop="操作">
                      <template #default="scope">
                        <el-button-group>
                          <el-button
                            type="primary"
                            size="small"
                            text
                            @click="onDataEdit(scope.row)"
                          >
                            <template #icon>
                              <el-icon>
                                <svg-icon name="ant-design:edit-filled" />
                              </el-icon>
                            </template>
                            编 辑</el-button
                          >

                          <el-button
                            type="danger"
                            text
                            size="small"
                            @click="onDataDel(scope.row)"
                          >
                            <template #icon>
                              <el-icon>
                                <svg-icon name="ep:close-bold" />
                              </el-icon>
                            </template>
                            删除
                          </el-button>
                        </el-button-group>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-col :span="2">
                    <span></span>
                  </el-col>
                </el-col>
              </el-row>
              <el-row style="height: 20px">
                <el-col :span="2"><span></span></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="selection" align="center" />
          <el-table-column
            prop="dictName"
            label="字典名称"
            width="220"
            align="center"
          />
          <el-table-column
            prop="dictType"
            label="字典类型"
            align="center"
            width="220"
          />

          <el-table-column
            prop="status"
            label="状态"
            width="120"
            align="center"
          >
            <template v-slot="scope">
              <el-tag v-if="scope.row.status == '0'" effect="Light"
                >正常</el-tag
              >
              <el-tag v-else effect="Light" type="warning">停用</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="createTime" label="创建时间" width="180">
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="onEdit(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:edit-filled" />
                    </el-icon>
                  </template>
                  编 辑</el-button
                >

                <el-button
                  type="danger"
                  text
                  size="small"
                  @click="onDel(scope.row)"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:close-bold" />
                    </el-icon>
                  </template>
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
    <DataFormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.dataformModeProps.id"
      :dictType="data.dataformModeProps.dictType"
      :dictName="data.dataformModeProps.dictName"
      v-model="data.dataformModeProps.visible"
      :mode="data.formMode"
      @success="load"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
.data-table {
  background-color: #f2f3f5;
  // #;
}
</style>
